
const express = require('express')
const app = express()
 
const cors = require('cors') //解决跨域问题
app.use(cors())
 
const bodyParser = require('body-parser')
const multiparty = require('connect-multiparty')
// 处理 x-www-form-urlencoded 
app.use(bodyParser.urlencoded({ extended: true }))
// 处理 mutipart/form-data
app.use(multiparty())
// 处理 application/json
app.use(bodyParser.json())

//导入连接数据库的函数
const DB = require('./mysql')

//MD5
const {md5} = require("./md5")

// token
const jwt = require("jsonwebtoken")
const secret = 'iloveyou';//加密私钥


//登录
app.post('/getUserInfo', (req, res) => {
    let {phone,password} = req.body;
    
    //明文密码==>密文密码
    password = md5(password);

	DB.exec({
        sql:`select * from users where userphone= ? and password =?`,
        params:[phone,password],
        callback(data){
            console.log(data[0]);
            if (data.length && "id" in data[0]) {
                let obj = {
                    id:data[0].id,
                    username:data[0].username,
                    userphone:data[0].userphone,
                    password:data[0].password
                }
                let token = jwt.sign(obj,secret);
                res.send({data,token,msg:'登录成功'})
                console.log("登录成功");
            }else{
                console.log("登录失败");
                res.send({
                    msg:'登录失败',
                    data:null,
                    status:301,
                })
            }
        }
    })
})

//注册数据
app.post("/registerPost",(req,res)=>{
    console.log(req.body);
    let {username,phone,password} = req.body;

    DB.exec({
        sql:`select * from users where userphone = ?`,
        params:[phone],
        callback(data){
            if (data.length && "id" in data[0]) {
                console.log("不允许注册");
                res.send({
                    msg:'已存在该用户！',
                    status:'error'
                });
            }else{
                console.log("允许注册");

                password = md5(password)
                DB.exec({
                    sql:`insert into users (username,userphone,password) values (?,?,?)`,
                    params:[username,phone,password],
                    callback(data){
                        res.send({
                            msg:'注册成功！',
                            status:'OK'
                        });
                    }
                })
            }
        }
    })
})
 
//监听node服务器的端口号
app.listen(3000, () => {
	console.log('服务器启动成功')
})